<template>
  <div class="forgot-password-page">
    <!-- 顶部导航 -->
    <van-nav-bar 
      title="忘记密码" 
      left-arrow 
      @click-left="goBack"
    />
    
    <!-- 表单内容 -->
    <div class="form-container">
      <!-- 步骤指示器 -->
      <van-steps :active="currentStep" direction="horizontal">
        <van-step>{{ isEmailMode ? '验证邮箱' : '验证手机号' }}</van-step>
        <van-step>重置密码</van-step>
        <van-step>完成</van-step>
      </van-steps>
      
      <!-- 步骤1: 验证手机号/邮箱 -->
      <div v-if="currentStep === 0" class="step-content">
        <div class="form-title">{{ isEmailMode ? '验证邮箱' : '验证手机号' }}</div>
        <div class="form-desc">请输入您注册时使用的{{ isEmailMode ? '邮箱' : '手机号' }}</div>
        
        <van-form @submit="checkAccount">
          <van-field
            v-if="isEmailMode"
            v-model="email"
            name="email"
            label="邮箱"
            placeholder="请输入邮箱"
            :rules="emailRules"
            type="email"
          />
          <van-field
            v-else
            v-model="phone"
            name="phone"
            label="手机号"
            placeholder="请输入手机号"
            :rules="phoneRules"
            type="tel"
            maxlength="11"
          />
          
          <div class="form-actions">
            <van-button 
              round 
              block 
              type="primary" 
              native-type="submit"
              :loading="checking"
            >
              下一步
            </van-button>
          </div>
        </van-form>
      </div>
      
      <!-- 步骤2: 重置密码 -->
      <div v-if="currentStep === 1" class="step-content">
        <div class="form-title">重置密码</div>
        <div class="form-desc">验证码已发送至 {{ isEmailMode ? email : phone }}</div>
        
        <van-form @submit="resetPassword">
          <van-field
            v-model="code"
            name="code"
            label="验证码"
            placeholder="请输入6位验证码"
            :rules="codeRules"
            type="number"
            maxlength="6"
          >
            <template #button>
              <van-button 
                size="small" 
                type="primary" 
                :disabled="codeCountdown > 0"
                @click="sendCode"
              >
                {{ codeCountdown > 0 ? `${codeCountdown}s后重发` : '发送验证码' }}
              </van-button>
            </template>
          </van-field>
          
          <van-field
            v-model="newPassword"
            name="newPassword"
            label="新密码"
            placeholder="请输入新密码"
            :rules="passwordRules"
            type="password"
            maxlength="20"
          />
          
          <van-field
            v-model="confirmPassword"
            name="confirmPassword"
            label="确认密码"
            placeholder="请再次输入新密码"
            :rules="confirmPasswordRules"
            type="password"
            maxlength="20"
          />
          
          <div class="form-actions">
            <van-button 
              round 
              block 
              type="primary" 
              native-type="submit"
              :loading="resetting"
            >
              重置密码
            </van-button>
          </div>
        </van-form>
      </div>
      
      <!-- 步骤3: 完成 -->
      <div v-if="currentStep === 2" class="step-content success-content">
        <div class="success-icon">✅</div>
        <div class="success-title">密码重置成功</div>
        <div class="success-desc">您可以使用新密码登录了</div>
        
        <div class="form-actions">
          <van-button 
            round 
            block 
            type="primary" 
            @click="goToLogin"
          >
            立即登录
          </van-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'
import { sendResetCode, resetPassword as resetPasswordApi, checkPhone as checkPhoneApi, checkEmail as checkEmailApi } from '@/api/forgot-password'

const router = useRouter()

// 响应式数据
const currentStep = ref(0)
const phone = ref('')
const email = ref('')
const code = ref('')
const newPassword = ref('')
const confirmPassword = ref('')
const checking = ref(false)
const resetting = ref(false)
const codeCountdown = ref(0)

// 获取路由参数，判断是否为邮箱模式
const route = useRoute()
const isEmailMode = ref(route.query.method === '1') // 1-邮箱，2-手机号

// 表单验证规则
const phoneRules = [
  { required: true, message: '请输入手机号' },
  { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
]

const emailRules = [
  { required: true, message: '请输入邮箱' },
  { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: '邮箱格式不正确' }
]

const codeRules = [
  { required: true, message: '请输入验证码' },
  { pattern: /^\d{6}$/, message: '验证码必须是6位数字' }
]

const passwordRules = [
  { required: true, message: '请输入新密码' },
  { min: 6, max: 20, message: '密码长度必须在6-20位之间' }
]

const confirmPasswordRules = [
  { required: true, message: '请确认密码' },
  { validator: (val) => val === newPassword.value, message: '两次输入的密码不一致' }
]

// 检查账户是否已注册
const checkAccount = async () => {
  const account = isEmailMode.value ? email.value : phone.value
  const accountType = isEmailMode.value ? '邮箱' : '手机号'
  
  if (!account) {
    showToast(`请输入${accountType}`)
    return
  }
  
  try {
    checking.value = true
    let result
    
    if (isEmailMode.value) {
      // 检查邮箱是否已注册
      result = await checkEmailApi(email.value)
    } else {
      // 检查手机号是否已注册
      result = await checkPhoneApi(phone.value)
    }
    
    if (result.isRegistered) {
      currentStep.value = 1
      showToast(`${accountType}验证成功`)
    } else {
      showToast(`该${accountType}未注册`)
    }
  } catch (error) {
    console.error(`检查${accountType}失败:`, error)
    showToast(`检查${accountType}失败，请稍后重试`)
  } finally {
    checking.value = false
  }
}

// 发送验证码
const sendCode = async () => {
  const account = isEmailMode.value ? email.value : phone.value
  const accountType = isEmailMode.value ? '邮箱' : '手机号'
  
  if (!account) {
    showToast(`请先输入${accountType}`)
    return
  }
  
  try {
    const result = await sendResetCode(account)
    
    if (result.success) {
      showToast('验证码发送成功')
      startCountdown()
    } else {
      showToast(result.message || '验证码发送失败')
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    showToast('验证码发送失败，请稍后重试')
  }
}

// 重置密码
const resetPassword = async () => {
  if (!code.value || !newPassword.value || !confirmPassword.value) {
    showToast('请填写完整信息')
    return
  }
  
  if (newPassword.value !== confirmPassword.value) {
    showToast('两次输入的密码不一致')
    return
  }
  
  try {
    resetting.value = true
    const account = isEmailMode.value ? email.value : phone.value
    const result = await resetPasswordApi(account, code.value, newPassword.value)
    
    if (result.success) {
      currentStep.value = 2
      showToast('密码重置成功')
    } else {
      showToast(result.message || '密码重置失败')
    }
  } catch (error) {
    console.error('重置密码失败:', error)
    showToast('密码重置失败，请稍后重试')
  } finally {
    resetting.value = false
  }
}

// 开始倒计时
const startCountdown = () => {
  codeCountdown.value = 60
  const timer = setInterval(() => {
    codeCountdown.value--
    if (codeCountdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 返回上一页
const goBack = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  } else {
    router.back()
  }
}

// 跳转到登录页
const goToLogin = () => {
  router.push('/login')
}
</script>

<style lang="scss" scoped>
.forgot-password-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.form-container {
  padding: 20px;
  background: #fff;
  margin: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.step-content {
  margin-top: 30px;
}

.form-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
  text-align: center;
}

.form-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 30px;
  text-align: center;
}

.form-actions {
  margin-top: 30px;
}

.success-content {
  text-align: center;
  padding: 20px 0;
}

.success-icon {
  font-size: 60px;
  margin-bottom: 20px;
}

.success-title {
  font-size: 20px;
  font-weight: bold;
  color: #52c41a;
  margin-bottom: 10px;
}

.success-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 30px;
}

:deep(.van-steps) {
  margin-bottom: 20px;
}

:deep(.van-field__button) {
  margin-left: 10px;
}
</style>
